package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.DeviceType;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.MySocket;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.listener.IInfraredSeneder;
import com.dotstone.chipism.listener.InfraredSeneder;
import com.dotstone.chipism.util.ConvertUtil;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;
import com.tiqiaa.client.IRemoteClient;
import com.tiqiaa.client.IRemoteClient.CallBackOnRemoteDownloaded;
import com.tiqiaa.client.IRemoteClient.CallbackOnMatchDone;
import com.tiqiaa.client.impl.RemoteClient;
import com.tiqiaa.constant.ApplianceType;
import com.tiqiaa.ircode.impl.InfraredFetcher;
import com.tiqiaa.irdnasdk.IrDnaSdkHelper;
import com.tiqiaa.remote.entity.Infrared;
import com.tiqiaa.remote.entity.Key;
import com.tiqiaa.remote.entity.MatchPage;
import com.tiqiaa.remote.entity.MatchPage.IRMark;
import com.tiqiaa.remote.entity.Remote;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class AddTvActivity1 extends BaseActivity implements CallbackOnMatchDone {
	private LinearLayout mBackL;
	private TextView mStatusBar;
	private Button mPowerB;
	private Button mSoundupB;
	private Button mSoundB;
	private Button mNumB;
	private Button mMenuB;
	private TextView mTitleTv;
	// private Button mSaveB;
	private Button mTvUpB;
	// private boolean power = true;
	// private Button mPreB;
	// private Button mNextB;
	private Button cancel_btn;
	private Button ensure_btn;
	private Vibrator vibrator;
	private int type;
	private String brand;
	private long brandId;
	private MySocket socket;
	private IRemoteClient client;
	private SVProgressHUD mSVProgressHUD;
	private int currentMatchIndex = 0;// 当前匹配的是第一个遥控器
	private Remote currentRemote;
	private List<Remote> matchRemotes = new ArrayList<Remote>(); // 当前匹配按键的所有遥控器，与按键有关
	// private Page page = new Page();
	private MatchPage matchPage = new MatchPage();
	private IInfraredSeneder mSeneder;
	// 精确匹配信号特征集合
	private List<IRMark> marks = new ArrayList<IRMark>();
	private List<Integer> failedKeys = new ArrayList<Integer>(); // 未匹配成功的按键，一个按键在所有的遥控器数据都匹配完后还没有匹配到，此时需要将它标记
	private List<Button> buttons = new ArrayList<Button>();
	private HashMap<Integer, String> irDataMaps = new HashMap<Integer, String>();
	private List<Key> keys = new ArrayList<Key>();
	private HashMap<Integer, String> cmdMaps = new HashMap<Integer, String>();
	private List<IRMark> failedmarks = new ArrayList<IRMark>();
	protected String selected_remote_id;
	private Dialog dialog;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;
		case R.id.power_b:
			sendCmd(800);
			vibrator.vibrate(50);
			break;
		case R.id.num_btn:
			sendCmd(1);
			vibrator.vibrate(50);
			break;
		case R.id.menu_btn:
			sendCmd(822);
			vibrator.vibrate(50);
			break;
		case R.id.sound_btn:
			sendCmd(804);
			vibrator.vibrate(50);
			break;
		case R.id.sound_up_btn:
			sendCmd(809);
			vibrator.vibrate(50);
			break;
		case R.id.tv_up_btn:
			// 频道+ 807
			vibrator.vibrate(50);
			sendCmd(807);
			break;
		case R.id.cancel_btn:
			dialog.dismiss();
			IRMark failedMarked = new IRMark();
			failedMarked.setIr_mark(currentRemote.getKeys().get(0).getInfrareds().get(0).getIr_mark());
			failedMarked.setKey_type(currentRemote.getKeys().get(0).getInfrareds().get(0).getKey_type());
			failedmarks.add(failedMarked);
			if (currentMatchIndex < matchRemotes.size() - 1) {
				currentMatchIndex++;
				currentRemote = matchRemotes.get(currentMatchIndex);
				mTitleTv.setText(
						"匹配" + brand + " 电视" + "(" + (currentMatchIndex + 1) + "/" + matchRemotes.size() + ")");
				refreshKey();
			} else {
				// 获取此按键的更多遥控器信号
				match();
			}

			break;
		case R.id.ensure_btn:
			dialog.dismiss();
			Log.i("wmy", "matchRemotes.size() = " + matchRemotes.size() + " currentMatchIndex = " + currentMatchIndex);
			selected_remote_id = currentRemote.getId();
			// 精确匹配信号特征
			IRMark okMarked = new IRMark();
			// 该特征的标签为遥控器第一个按键的红外码的标签
			okMarked.setIr_mark(currentRemote.getKeys().get(0).getInfrareds().get(0).getIr_mark());
			// 该特征的按键类型为遥控器第一个按键的红外码的按键类型
			okMarked.setKey_type(currentRemote.getKeys().get(0).getInfrareds().get(0).getKey_type());
			// 将该特征添加至特征的集合中
			marks.add(okMarked);
			// 将失败的特征码清除
			failedmarks.clear();
			// 将当前已匹配的所有遥控器的集合清除 以便获取新案件的匹配遥控器时不重复添加
			matchRemotes.clear();
			// 当前所选遥控器的位置为0
			currentMatchIndex = 0;
			// 重新获取新按键的匹配遥控器
			mSVProgressHUD.showWithStatus("正在加载");
			match();

			break;
		default:

			break;
		}
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_tv1;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mBackL = $(R.id.back_layout);
		mStatusBar = $(R.id.tv_statusBar_mian);
		mTitleTv = $(R.id.title_tv);
		mPowerB = $(R.id.power_b);
		mSoundupB = $(R.id.sound_up_btn);
		mSoundB = $(R.id.sound_btn);
		mSoundupB = $(R.id.sound_up_btn);
		mNumB = $(R.id.num_btn);
		mMenuB = $(R.id.menu_btn);
		mTvUpB = $(R.id.tv_up_btn);
		buttons.add(mPowerB);
		buttons.add(mSoundupB);
		buttons.add(mSoundB);
		buttons.add(mNumB);
		buttons.add(mMenuB);
		buttons.add(mTvUpB);
		boolVersion();
		mBackL.setOnClickListener(this);
		mPowerB.setOnClickListener(this);
		mSoundB.setOnClickListener(this);
		mSoundupB.setOnClickListener(this);
		mMenuB.setOnClickListener(this);
		mNumB.setOnClickListener(this);
		mTvUpB.setOnClickListener(this);
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		type = getIntent().getIntExtra("type", 999);
		brand = getIntent().getStringExtra("brand");
		brandId = getIntent().getLongExtra("brandId", 999);
		socket = SocketManager.getInstance().sMap.get(DeviceManager.getInstance().getmWlanId());
		if (socket == null) {
			ToastShow.Show(getApplicationContext(), "请重新选择网关再添加！");
			finish();
		}
		client = new RemoteClient(getApplicationContext());
		mSeneder = new InfraredSeneder(getApplicationContext());
		mSVProgressHUD = new SVProgressHUD(AddTvActivity1.this);
		setListeners();
	}

	private void setListeners() {
		matchRemotes.clear();
		currentMatchIndex = 0;
		mSVProgressHUD.showWithStatus("正在加载");
		match();
	}

	protected void match() {
		Log.i("wmy", "type = " + type + " brandId = " + brandId);
		matchPage.setAppliance_type(ApplianceType.TV);
		matchPage.setBrand_id(brandId);
		matchPage.setOkMarks(marks);
		matchPage.setWrongMarks(failedmarks);
		matchPage.setFailedKeys(failedKeys);
		client.exactMatchReomtes(matchPage, true, AddTvActivity1.this);
	}

	private void sendCmd(int id) {
		Key key = null;
		for (int i = 0; i < currentRemote.getKeys().size(); i++) {
			if (currentRemote.getKeys().get(i).getType() == id) {
				key = currentRemote.getKeys().get(i);
			}
		}
		if (key != null) {
			mSeneder.send(currentRemote, key);
			vibrator.vibrate(50);
		}
		showConfirmDialog();
	}

	// 保存该遥控器
	private void save() {
		// 上传设备
		RequestParams params = new RequestParams(HttpURL.UPLOAD_DEVICE_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("classification", "4");
			obj.put("key", "10000");
			obj.put("deviceModel", currentRemote.getId());
			obj.put("deviceName", "电视 " + brand + " " + currentRemote.getModel());
			obj.put("deviceType", type + "");
			obj.put("deviceVersion", "3.1.0");
			obj.put("deviceWifiSSID", currentRemote.getId().equals("") ? "未知" : currentRemote.getId());
			obj.put("deviceId", "0");
			obj.put("productId", "4");
			obj.put("mainDeviceId", DeviceManager.getInstance().getmWlanId());
			obj.put("hid", DeviceManager.getInstance().hid);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			Log.e("wmy", " upload tv remote = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("wmy", "upload tv remote result =" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					String value = jsonObject.getString("resultCode");
					if (value.equals("1")) {
						String deviceId = jsonObject.getString("data");
						// 获取deviceId之后 上传所有按键
						uploadKeys(deviceId);
					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), "保存失败：" + errorMsg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void uploadKeys(String deviceId) {
		initKey();
		// 上传按键
		String buttonCmdS = "";
		String positionS = "";
		String nameS = "";
		for (int i = 0; i < keys.size(); i++) {
			if (cmdMaps.get(keys.get(i).getType()) != null) {
				buttonCmdS += irDataMaps.get(keys.get(i).getType()) + ",";
				positionS += keys.get(i).getType() + ",";
				nameS += keys.get(i).getLocalName() + ",";
			}
		}
		if (buttonCmdS.length() > 1) {
			buttonCmdS = buttonCmdS.substring(0, buttonCmdS.length() - 1);
		}
		if (positionS.length() > 1) {
			positionS = positionS.substring(0, positionS.length() - 1);
		}
		if (nameS.length() > 1) {
			nameS = nameS.substring(0, nameS.length() - 1);
		}
		RequestParams params = new RequestParams(HttpURL.UPLOAD_REMOTE_KEY_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("buttonCmdS", buttonCmdS);
			obj.put("key", "10000");
			obj.put("positionS", positionS);
			obj.put("nameS", nameS);
			obj.put("deviceId", deviceId);
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			Log.e("wmy", " upload tv key obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("wmy", "upload tv key result=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					String value = jsonObject.getString("resultCode");
					if (value.equals("1")) {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						ToastShow.Show(getApplicationContext(), "保存成功");
						finish();
					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), "保存失败：" + errorMsg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void initKey() {
		keys = currentRemote.getKeys();
		for (int i = 0; i < keys.size(); i++) {
			List<Infrared> infrareds = null;
			infrareds = new InfraredFetcher(this).fetchInfrareds(currentRemote, keys.get(i));
			if (infrareds != null) {
				for (Infrared ir : infrareds) {
					if (ir != null && ir.getData() != null) {
						// int freq = ir.getFreq();
						// Required ！ 必须调用，此接口将对信号格式进行验证，返回明码信号数据
						// Log.i("wmy", "ir.getData() = "+ir.getData());
						byte[] data = IrDnaSdkHelper.getIrCode(ir.getFreq(), ir.getData());
						// byte[] airData =
						// IrDnaSdkHelper.getAirVMCode(keys.get(i).getProtocol());
						// data格式详见《信号数据格式说明》文档，不同的芯片需要转换成对应的芯片目标码
						// String str = byte2HexStr(data);
						String str = Util.bytesToHexString(data).toUpperCase();
						String cmd = ConvertUtil.getInstance().convertInfraredCmd(str);
						// Log.w("wmy",
						// "send....###..解析出的红外数据..data = "+cmd+" " +
						// Arrays.toString(data));
						Log.e("wmy", "电视 " + keys.get(i).getType() + " " + keys.get(i).getLocalName());
						cmdMaps.put(keys.get(i).getType(), cmd);
						irDataMaps.put(keys.get(i).getType(), str);
					}
				}
			}
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	@Override
	public void onMatchDone(int errcode, List<Remote> remotes) {
		// TODO Auto-generated method stub
		if (mSVProgressHUD.isShowing()) {
			mSVProgressHUD.dismiss();
		}
		if (errcode == CallbackOnMatchDone.ERROR_CODE_SUCCESS) {
			if (remotes != null && remotes.size() > 0) {
				matchRemotes.addAll(remotes);
				currentRemote = matchRemotes.get(currentMatchIndex);
				refreshMatchView();
			} else {
				// showToast("无更多遥控器,忽略此按键");
				failedKeys.add(matchPage.getNext_key());
				// 此按键匹配失败，忽略此按键，匹配下一个按键，
				failedmarks.clear();
				matchRemotes.clear();
				currentMatchIndex = 0;
				match();
			}
		} else if (errcode == CallbackOnMatchDone.ERROR_MATCH_COMPLETED && selected_remote_id != null) {
			showSuccessDialog();
		} else {
			showToast("匹配失败");
			Intent intent = new Intent(AddTvActivity1.this, ModelSelectionActivity1.class);
			intent.putExtra("type", DeviceType.DEVICE_TYPE_TV);
			intent.putExtra("brand", brand);
			intent.putExtra("brandId", brandId);
			startActivity(intent);
			//finish();
		}
	}

	private void showSuccessDialog() {
		IRemoteClient client = new RemoteClient(getApplicationContext());
		client.download_reomte(selected_remote_id, new CallBackOnRemoteDownloaded() {
			@Override
			public void onRemoteDownloaded(int errcode, final Remote remote1) {
				if (errcode != CallBackOnRemoteDownloaded.ERROR_CODE_SUCCESS) {
					showToast("下载遥控器失败,请重试");
					finish();
				} else {
					currentRemote = remote1;
					boolean e = DeviceManager.getInstance().checkName("电视 " + brand + " " + remote1.getModel());
					if (e) {
						ToastShow.Show(getApplicationContext(),
								"匹配成功，遥控器：电视 " + brand + " " + remote1.getModel() + "已存在，无需添加");
						finish();
					} else {
						save();
					}
				}
			}
		});
	}

	private void refreshMatchView() {
		mTitleTv.setText("匹配" + brand + " 电视" + "(" + (currentMatchIndex + 1) + "/" + matchRemotes.size() + ")");
		if (currentMatchIndex == 0) {
			refreshKey();
		}
	}

	// 刷新当前匹配的按键
	private void refreshKey() {
		Log.i("wmy", "refreshKey 当前按键的type = " + matchRemotes.get(currentMatchIndex).getKeys().get(0).getType());
		Log.i("wmy", "refreshKey 当前按键的IR特征 = "
				+ matchRemotes.get(currentMatchIndex).getKeys().get(0).getInfrareds().get(0).getIr_mark());
		switch (matchRemotes.get(currentMatchIndex).getKeys().get(0).getType()) {
		case 800: // 电源
			resetBg();
			mPowerB.setClickable(true);
			mPowerB.setBackgroundResource(R.drawable.kaiguan12x);
			break;
		case 809: // 音量+
			resetBg();
			mSoundupB.setClickable(true);
			mSoundupB.setBackgroundResource(R.drawable.selector_sound_up);
			break;
		case 804: // 静音
			resetBg();
			mSoundB.setClickable(true);
			mSoundB.setBackgroundResource(R.drawable.selector_shengyin1);
			break;
		case 805: // 123 选台
			resetBg();
			mNumB.setClickable(true);
			mNumB.setBackgroundResource(R.drawable.selector_num);
			break;
		case 822: // 菜单
			resetBg();
			mMenuB.setClickable(true);
			mMenuB.setBackgroundResource(R.drawable.selector_menu);
			break;
		case 807:// 频道+
			resetBg();
			mTvUpB.setClickable(true);
			mTvUpB.setBackgroundResource(R.drawable.selector_tv_up);
			break;
		case 1:
			resetBg();
			mNumB.setClickable(true);
			mNumB.setBackgroundResource(R.drawable.selector_num);
			break;
		default:
			break;
		}
	}

	private void resetBg() {
		for (int i = 0; i < buttons.size(); i++) {
			buttons.get(i).setClickable(false);
		}
		mPowerB.setBackgroundResource(R.drawable.kaiguan32x);
		mSoundupB.setBackgroundResource(R.drawable.kuang2x);
		mSoundB.setBackgroundResource(R.drawable.kuang2x);
		mNumB.setBackgroundResource(R.drawable.kuang2x);
		mMenuB.setBackgroundResource(R.drawable.kuang2x);
		mTvUpB.setBackgroundResource(R.drawable.kuang2x);
	}

	private void showConfirmDialog() {
		dialog = new Dialog(AddTvActivity1.this);
		dialog.setContentView(R.layout.dialog_confirm_respond);
		TextView remind_tv = (TextView) dialog.findViewById(R.id.remind_tv);
		remind_tv.setText("请观察电视是否有正确响应");
		cancel_btn = (Button) dialog.findViewById(R.id.cancel_btn);
		ensure_btn = (Button) dialog.findViewById(R.id.ensure_btn);
		cancel_btn.setOnClickListener(this);
		ensure_btn.setOnClickListener(this);
		dialog.setCancelable(false);
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
	}

}
